
package com.tools.cleanmaster.model.db;

import android.content.Context;

import com.tools.cleanmaster.CleanApplication;
import com.tools.cleanmaster.store.DatabaseUpdateSharePrefManager;
import com.tools.cleanmaster.utils.FeatureConfig;
import com.tools.cleanmaster.utils.FileHelper;
import com.tools.cleanmaster.utils.JsonUtils;
import com.tools.cleanmaster.utils.LogHelper;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;

public class TrashWhiteListItem extends DatabaseUpdatePuller.DatabaseUpdatePullerItem {
    static final String LOG_TAG = "TrashWhiteListItem";
    private static final int DB_VERSION = 1;

    @Override
    public String getUpdateId() {
        return DatabaseUpdateConstants.DB_ID_TRASH_WHITELIST;
    }

    @Override
    public File getLocalDbPath(Context ctx) {
        return ctx.getFileStreamPath(getDbName());
    }

    @Override
    public int getDbVersion() {
        return DatabaseUpdateSharePrefManager.getCurDbConfigVersion(CleanApplication.getInstance(),
                getUpdateId(), -1);
    }

    @Override
    public int getDbFormatVersion() {
        return 0;
    }

    @Override
    public void notifyUpgraded() {
        Context context = CleanApplication.getInstance();
        InputStream is = null;
        try {
            is = context.openFileInput(
                    DatabaseUpdateConstants.DB_NAME_TRASH_WHITELIST);
            String jsonStr = JsonUtils.readFromStream(is);
            JSONObject root = new JSONObject(jsonStr);
            JSONArray jsonDatas = root.getJSONArray("datas");
            ArrayList<WhiteListBean> beans = new ArrayList<WhiteListBean>();
            for (int i = 0, len = jsonDatas.length(); i < len; i++) {
                JSONObject data = jsonDatas.getJSONObject(i);
                WhiteListBean bean = new WhiteListBean();
                bean.filePath = data.getString("filePath");
                bean.pkgName = data.getString("pkgName");
                bean.type = data.getInt("type");
                beans.add(bean);
            }
            TrashDB trashDB = TrashDB.getInstance();
            trashDB.cleanAndInsertIntoWhiteList(beans);
        } catch (FileNotFoundException e) {
            if (FeatureConfig.DEBUG_LOG) {
                LogHelper.e(LOG_TAG, "update db failed.", e);
            }
        } catch (JSONException e) {
            if (FeatureConfig.DEBUG_LOG) {
                LogHelper.e(LOG_TAG, "update db failed.", e);
            }
        } finally {
            FileHelper.close(is);
        }
    }

    @Override
    public String getDbName() {
        return DatabaseUpdateConstants.DB_NAME_TRASH_WHITELIST;
    }

    @Override
    public int getAssetDbVersion() {
        return DB_VERSION;
    }
}
